﻿using CommonTools;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shop.Bll.daifa
{
    public class NeedBuyerInfoBll : BasePageBll<NeedBuyerInfo>
    {
        public override string Title => "代发登记";

        public override bool EnableEditOnList => true;

        public bool EnableCreateOnList => true;

        public override bool RefreshOnOpen => false;

        public override NeedBuyerInfo CopyItem(NeedBuyerInfo item)
        {
            if (item == null)
                return null;

            var newItem = item.Clone();
            newItem.id = 0;
            newItem.isdel = false;

            return newItem;
        }

        public override NeedBuyerInfo CreateItem()
        {
            return new NeedBuyerInfo() { isdel = false, FUser = UserBll.CurrentUser.Name, FTime = DateTime.Now,};
        }

        public override async Task<Result> DeleteItem(int id)
        {
            await DB.FSql.Update<NeedBuyerInfo>()
                .Where(a => a.id == id && a.isdel == false)
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();

            //await DB.FSql.Insert(new CLogs()
            //{
            //    DocName = nameof(NeedBuyerInfo),
            //    Computer = UserBll.CurrentUser.ComputerInfo,
            //    Zdr = UserBll.CurrentUser.Name,
            //    DocId = id.ToString(),
            //    DocAction = "删除",
            //})
            //    .ExecuteAffrowsAsync();

            return new Result(true);
        }


        public override async Task<Result<int>> EditCell(string dataPropertyName, object value,  NeedBuyerInfo data)
        {
            if (data.id == 0)
            {
                data.FTime = await DB.FSql.GetTimeAsync();
                data.FUser = UserBll.CurrentUser.Name;
                data.isdel = false;

                var nid = await DB.FSql.Insert(data)
                    .ExecuteIdentityAsync();

                data.id = (int)nid;
            }

            var dict = new Dictionary<string, object> { [dataPropertyName] = value };

            if(dataPropertyName == nameof(NeedBuyerInfo.ShopName))
            {

            }

            var dbRes = await DB.FSql.Update<NeedBuyerInfo>()
                .Where(a => a.id == data.id && a.isdel == false)
                .SetDto(dict)
                .ExecuteAffrowsAsync();

            return new Result<int>(true, "!", data.id);
        }

        public override IEnumerable<DeclareColumn> GetColumns()
        {
            return new[]
            {
                new DeclareColumn(nameof(NeedBuyerInfo.id),"id"){ Visible= false},
                //new DeclareColumn(nameof(NeedBuyerInfo.FTime),"日期"){ Width=110, ValueType=typeof(DateTime) },
                new DeclareColumn(nameof(NeedBuyerInfo.FTime),"日期"){ Width=110, ValueType=typeof(DateTime) },
                new DeclareColumn(nameof(NeedBuyerInfo.ShopName),"店铺"){ Width=200 },
                new DeclareColumn(nameof(NeedBuyerInfo.src_tids),"原始单号"){ Width=180 , ValueType= typeof(string), Format="@"},
                new DeclareColumn(nameof(NeedBuyerInfo.TradeNo),"订单编号"){ Width=150, ValueType= typeof(string), Format="@" },
                new DeclareColumn(nameof(NeedBuyerInfo.BuyerName),"姓名"){ Width=110, },
                new DeclareColumn(nameof(NeedBuyerInfo.Phone),"电话"){ Width=105, },
                new DeclareColumn(nameof(NeedBuyerInfo.BuyerAddress),"地址"){ Width=220, },

                new DeclareColumn(nameof(NeedBuyerInfo.Qty),"数量"){ Width=66, },
                new DeclareColumn(nameof(NeedBuyerInfo.Stock),"仓库"){ Width=170},
                new DeclareColumn(nameof(NeedBuyerInfo.spec_no),"商家编码"){ Width=170},
                new DeclareColumn(nameof(NeedBuyerInfo.FUser),"制单人"){ ReadOnly= true},
                new DeclareColumn(nameof(NeedBuyerInfo.IsOk),"是否查询完成"){ ReadOnly= true,},
                new DeclareColumn(nameof(NeedBuyerInfo.noInfo),"查询异常"){ ReadOnly= true,},
                new DeclareColumn(nameof(NeedBuyerInfo.IsDelivery),"是否发货"){ ReadOnly= true,},
            };
        }

        public override async Task<NeedBuyerInfo> GetItem(int id)
        {
            return await DB.FSql.Select<NeedBuyerInfo>()
                .Where(a => a.isdel == false && a.id == id)
                .ToOneAsync();
        }


        #region 查询参数

        private string _tradeNo;
        //private string _logiNo;
        private string _specno;
        private string _src_tids;
        private string _shop;
        private string _spec_no;
        private string _stock;
        private DateTime? _begin;
        private DateTime? _end;

        #endregion

        /// <summary> 查询ui </summary>
        public override ControlBuilder GetUIBuilder()
        {
            return new ControlBuilder()
                .Add<DateTime?>(ControlEnum.gtDatePicker, "起始日期", c => _begin= c)
                .Add<DateTime?>(ControlEnum.gtDatePicker, "截止日期", c => _end= c)
                .Add<string>(ControlEnum.guanTextBox, "店铺", c => _shop= c)
                .SetFlowBreak()
                .Add<string>(ControlEnum.guanTextBox, "原始单号", c => _src_tids = c)
                .Add<string>(ControlEnum.guanTextBox, "商家编码", c => _specno= c)
                .Add<string>(ControlEnum.guanTextBox, "订单编号", c => _tradeNo = c)
                .Add<string>(ControlEnum.guanTextBox, "仓库", c => _stock = c)
                //.Add<string>(ControlEnum.guanTextBox, "物流单号", c => _logiNo = c)
                .SetFlowBreak()
                .AddQueryButton("查询");
        }

        /// <summary> 查询 </summary>
        public override async Task<PageQueryResult<NeedBuyerInfo>> QueryPage(DocFilterParameter queryPara)
        {
            _end = _end.LastTimeOfDay();

            var list = await DB.FSql.Select<NeedBuyerInfo>()
                .Where(a => a.isdel == false)
                .WhereIf(_begin != null, a => a.FTime >= _begin.Value.Date )
                .WhereIf(_end != null, a => a.FTime <= _end.Value.Date )
                .WhereIf(!string.IsNullOrEmpty(_src_tids), a => a.src_tids == _src_tids)
                //.WhereIf(!string.IsNullOrEmpty(_logiNo), a => a.LogiNo.Contains(_logiNo))
                .WhereIf(!string.IsNullOrEmpty(_tradeNo), a => a.TradeNo.Contains(_tradeNo))
                .WhereIf(!string.IsNullOrEmpty(_shop), a => a.ShopName.Contains(_shop))
                .WhereIf(!string.IsNullOrEmpty(_spec_no), a => a.spec_no.Contains(_spec_no))
                .WhereIf(!string.IsNullOrEmpty(_stock), a => a.Stock.Contains(_stock))
                .Page(queryPara.PageNo, queryPara.PageSize)
                .OrderBy(a => a.FTime)
                .OrderBy(a => a.ShopName)
                .Count(out var c)
                .ToListAsync();

            return new PageQueryResult<NeedBuyerInfo>(true, null, list, c);
        }



        public override async Task<Result> SaveItem(NeedBuyerInfo item)
        {
            if (item == null)
            {
                return new Result(false, "系统错误");
            }

            string err = string.Empty;
            if (string.IsNullOrEmpty(item.TradeNo))
            {
                err += "订单编号不能为空!";
            }
            if (string.IsNullOrEmpty(item.src_tids))
            {
                err += "原始单号不能为空!";
            }

            if (string.IsNullOrEmpty(err) == false)
            {
                return new Result(false, err);
            }

            item.isdel = false;
            item.FTime = await DB.FSql.GetTimeAsync();
            item.FUser = UserBll.CurrentUser.Name;

            if (item.id <= 0)
            {
                var id = await DB.FSql.Insert(item)
                    .ExecuteIdentityAsync();

                item.id = (int)id;
            }
            else
            {
                await DB.FSql.Update<NeedBuyerInfo>()
                    .SetSource(item)
                    .ExecuteAffrowsAsync();
            }

            return new Result(true);
        }


        private string GetShopPlat(string shopName)
        {

            if (shopName.Contains("拼"))
            {
                return "拼多多";
            }
            else if (shopName.Contains("淘"))
            {
                return "淘宝";
            }
            else if (shopName.Contains("天猫"))
            {
                return "淘宝";
            }
            else if (shopName.StartsWith("京-"))
            {
                return "京东";
            }

            return string.Empty;
        }

        public async Task<Result> SaveItem(IEnumerable<NeedBuyerInfo> items)
        {
            if (items == null)
            {
                return new Result(false, "系统错误");
            }

            var time = await DB.FSql.GetTimeAsync(); 

            foreach (var item in items)
            {
                item.isdel = false;
                item.FTime = time;
                item.FUser = UserBll.CurrentUser.Name;
                item.PlatName = GetShopPlat(item.ShopName);
            }

            //去除重复的


            await DB.FSql.Insert(items).ExecuteAffrowsAsync();

            return new Result(true);

        }

        /// <summary>  </summary>
        public async Task<IEnumerable<NeedBuyerInfo>> FindTrades(DateTime? begin, DateTime? end, string spec_no,
            string src_tids)
        {
            var list = await DB.FSql.Select<OutStockItem>()
                .Where(a=> a.trade_time >= begin && a.trade_time<= end)
                .WhereIf(!string.IsNullOrEmpty(spec_no), a => a.spec_no.Contains(spec_no))
                .WhereIf(!string.IsNullOrEmpty(src_tids), a => a.src_tids.Contains(src_tids))
                .ToListAsync(a=> new NeedBuyerInfo()
                {
                    //LogiNo= a.logistics_no,
                    ShopName=a.shop_name,
                    src_tids= a.src_tids,
                    TradeNo= a.trade_no,
                    Qty = a.num,
                });

            foreach (var item in list)
            {
                item.FTime = DateTime.Today;
                item.FUser= UserBll.CurrentUser.Name;
                item.isdel = false;
                item.PlatName = GetShopPlat(item.ShopName);

            }
            return list;
        }

        public async Task ModifyIsOkField(int item, bool isok)
        {
            await DB.FSql.Update<NeedBuyerInfo>()
                .Where(a => a.id == item)
                .Set(a => a.IsOk, isok)
                .ExecuteAffrowsAsync();
        }



    }
}
